package com.example.sale.user;

import cn.hutool.db.PageResult;
import com.example.sale.dto.UserQuery;
import com.example.sale.mybatis.entity.User;
import com.example.sale.mybatis.mapper.UserMapper;
import com.example.sale.utils.SnowflakeIdGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigInteger;
import java.util.Date;
import java.util.List;

@Component
public class UserDaoImpl implements UserDao {

    @Autowired
    UserMapper usermapper;
    @Autowired
    SnowflakeIdGenerator snowflakeIdGenerator;

    @Override
    public int insertUser(User user) {
        if(user.getUserId()==null){
            user.setUserId(snowflakeIdGenerator.nextBigIntegerId());
        }
        if(user.getCreatedDt()==null){
            user.setCreatedDt(new Date());
        }
        if(user.getUpdatedDt()==null){
            user.setUpdatedDt(new Date());
        }
        return usermapper.insertUser(user);
    }

    @Override
    public User selectUserById(BigInteger userId) {
        return usermapper.selectUserById(userId);
    }

    @Override
    public User selectUserByUsername(String username) {
        return usermapper.selectUserByUsername(username);
    }

    @Override
    public User selectUserByEmail(String email) {
        return usermapper.selectUserByEmail(email);
    }

    @Override
    public List<User> selectUsers(User user) {
        return usermapper.selectUsers(user);
    }

    @Override
    public PageInfo<User> selectUsersByPage(UserQuery query) {
        // 开始分页
        PageHelper.startPage(query.getPageNum(), query.getPageSize());

        User user = new User();
        user.setUserId(query.getUserId());
        user.setUsername(query.getUsername());
        user.setEmail(query.getEmail());

        // 查询数据
        List<User> userList = usermapper.selectUsers(user);
        // 封装分页结果
        return new PageInfo<>(userList);
    }

    @Override
    public int updateUser(User user) {
        return usermapper.updateUser(user);
    }

    @Override
    public int deleteUserById(BigInteger userId) {
        return usermapper.deleteUserById(userId);
    }


}